package org.zjx.swing.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;

public class ImageDisplayPanel extends JPanel {
    private BufferedImage image;

    public ImageDisplayPanel() {
        this.setBackground(Color.GRAY);  // 设置默认背景色为灰色
    }

    // 设置图像，并更新面板的尺寸
    public void setImage(BufferedImage image) {
        this.image = image;
        revalidate();
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            // 获取面板的宽度和高度
            int panelWidth = getWidth();
            int panelHeight = getHeight();

            // 判断图像是否小于面板，如果是则进行缩放
            if (image.getWidth() < panelWidth && image.getHeight() < panelHeight) {
                // 计算缩放比例，保持宽高比
                double widthRatio = (double) panelWidth / image.getWidth();
                double heightRatio = (double) panelHeight / image.getHeight();
                double scale = Math.min(widthRatio, heightRatio);  // 选择最小的比例来保持宽高比

                // 计算缩放后的图像宽度和高度
                int width = (int) (image.getWidth() * scale);
                int height = (int) (image.getHeight() * scale);

                // 将图像绘制到面板上，居中显示
                int x = (panelWidth - width) / 2;
                int y = (panelHeight - height) / 2;
                g.drawImage(image, x, y, width, height, this);
            } else {
                // 如果图像大于面板，直接绘制图像的原始尺寸
                int x = (panelWidth - image.getWidth()) / 2;
                int y = (panelHeight - image.getHeight()) / 2;
                g.drawImage(image, x, y, this);
            }
        }
    }
}
